import socket
import time
from threading import Thread

from configs.config import *

g_open = b"\xA0\x01\x00\xA1"
g_close = b"\xA0\x01\x01\xA2"

y_open = b"\xA0\x02\x01\xA3"
y_close = b"\xA0\x02\x00\xA2"

r_open = b"\xA0\x03\x01\xA4"
r_close = b"\xA0\x03\x00\xA3"


class Alarm:
    def __init__(self, server_name, server_port):

        self.s = self.connect(server_name, server_port)
        self.port = server_port

    def connect(self, server_name, server_port):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.settimeout(1)
            s.connect((server_name, server_port))
        except BaseException:
            s = None
            print("alarm connect error")
        ret = s
        return ret

    def close_red(self):
        msg = str(self.port) + ': close_red'
        self.s.send(msg.encode('utf-8'))

    def close_yellow(self):
        msg = str(self.port) + ': close_yellow'
        self.s.send(msg.encode('utf-8'))

    def close_green(self):
        msg = str(self.port) + ': close_green'
        self.s.send(msg.encode('utf-8'))

    def set_green(self):
        msg = str(self.port) + ': set_green'
        self.s.send(msg.encode('utf-8'))

    def set_red(self):
        msg = str(self.port) + ': set_red'
        self.s.send(msg.encode('utf-8'))

    def set_yellow(self):
        msg = str(self.port) + ': set_yellow'
        self.s.send(msg.encode('utf-8'))


alarm_signal_dict = signal_dict.copy()


class ThreadAlarm:
    def __init__(self, name, server_name):
        self.alarm = Alarm(server_name, server_port)
        self.flag = True
        self.ret = self.start(name)

    def start(self, name):
        if self.alarm.s is not None:
            thread = Thread(target=self.threads, args=(name,))
            thread.daemon = True
            thread.start()
            return alarm_link_success
        else:
            return alarm_link_failed

    def threads(self, name):
        while True:
            if alarm_signal_dict[name] == 1:
                self.flag = True
                self.alarm.close_green()
                self.alarm.set_red()
                time.sleep(0.5)
                self.alarm.close_red()
                time.sleep(0.5)
            if alarm_signal_dict[name] == 2:
                self.flag = True
                self.alarm.close_green()
                self.alarm.set_yellow()
                time.sleep(0.5)
                self.alarm.close_yellow()
                time.sleep(0.5)
            if alarm_signal_dict[name] == 0:
                if self.flag:
                    self.flag = False
                    self.alarm.set_green()
                time.sleep(0.5)


def send_signal(judgment_dict: dict, preds_dict: dict, alarm_dict: dict):
    for name in alarm_dict.keys():
        if judgment_dict[name]:
            alarm_signal_dict[name] = 1
        elif preds_dict[name]:
            alarm_signal_dict[name] = 2
        else:
            alarm_signal_dict[name] = 0
